# --*-- conding:utf-8 --*--
# @Time : 2025/6/20 10:39
# @Author : Xu
# @Email : wsxzy98@outlook.com
# @File : controllers.py
# @Software : VScode

from odoo import http, fields
from odoo.http import Controller, request, route
from odoo.addons.stock_barcode.controllers.stock_barcode import StockBarcodeController

class GsStock(StockBarcodeController):
    @route('/gs_stock/mark_scan', type='json', auth='user', csrf=False)
    def mark_scan(self, line_id):
        ml = request.env['stock.move.line'].browse(int(line_id))
        ml.check_access_rights('write')
        ml.check_access_rule('write')
        now = fields.Datetime.now()
        # 只写我们自己的时间字段，避免触发 qty_done 等逻辑
        ml.with_context(skip_last_scan_time=True).write({'x_last_scan_time': now})
        # 返回用户时区格式的字符串（供前端直接展示/排序一致）
        local = fields.Datetime.context_timestamp(request.env.user, now)
        return {'ts': local.strftime('%Y-%m-%d %H:%M:%S')}
    
    @http.route('/stock_barcode/get_barcode_data', type='json', auth='user', csrf=False)
    def get_barcode_data(self, model, res_id):
        """
        扩展原有的get_barcode_data接口，确保无论是普通拣货单还是wave拣货（多个拣货单合并），
        每一条move line都能显示自己的原产地和客户参考号，避免wave下部分明细数据丢失。
        """
        # 调用原生父类，获得PDA扫码要展示的基础数据结构
        response = super().get_barcode_data(model, res_id)

        # （1）获取所有move line的json数据
        move_line_data_list = response['data']['records'].get('stock.move.line', [])

        # （2）提取所有move line的id（确保wave下多单也能全覆盖）
        move_line_ids = [line['id'] for line in move_line_data_list if 'id' in line]

        # （3）批量查找所有move line对象，避免N+1性能问题
        move_line_objs = request.env['stock.move.line'].browse(move_line_ids)

        # （4）构建id与原产地、客户参考号的对应关系
        move_line_id2origin = {ml.id: ml.origin_name or '' for ml in move_line_objs}
        move_line_id2reference = {ml.id: ml.customer_reference or '' for ml in move_line_objs}
        # 最近扫描时间；前端排序/显示都能用
        move_line_id2last = {ml.id: ml.x_last_scan_time or '' for ml in move_line_objs}

        # （5）给每个move line写入自定义字段
        for line in move_line_data_list:
            line['origin_name'] = move_line_id2origin.get(line['id'], '')
            line['customer_reference'] = move_line_id2reference.get(line['id'], '')
            dt = move_line_id2last.get(line['id'])
            if dt:
                # 统一转成 datetime，再按用户时区本地化
                dt_obj = fields.Datetime.from_string(dt) if isinstance(dt, str) else dt
                local_dt = fields.Datetime.context_timestamp(request.env.user, dt_obj)
                line_dt = local_dt.strftime('%Y-%m-%d %H:%M:%S')
            else:
                line_dt = False
            line['x_last_scan_time'] = line_dt

        # （6）原有全局picking客户参考号，可以根据需要保留
        picking_list = response['data']['records'].get('stock.picking', [])
        if picking_list and 'id' in picking_list[0]:
            picking_id = picking_list[0]['id']
            picking = request.env['stock.picking'].browse(picking_id)
            # 这里存的是第一个picking的客户参考号（PDA全局展示用，非明细用）
            if 'stock.location' in response['data']['records']:
                response['data']['records']['stock.location'][0]['customer_reference'] = picking.customer_reference

        return response
# class GsStock(StockBarcodeController):
#     @http.route('/stock_barcode/get_barcode_data', type='json', auth='user', csrf=False)
#     def get_barcode_data(self, model, res_id):
#         response = super().get_barcode_data(model, res_id)
#         picking_list = response['data']['records']['stock.picking']
#         picking_id = picking_list[0].get('id', None)
#         if picking_id:
#             picking = request.env['stock.picking'].browse(picking_id)
#             # 这里全局的客户参考号可以保留（如有特殊用途），但建议产品行自己显示
#             response['data']['records']['stock.location'][0]['customer_reference'] = picking.customer_reference
        
#         # 新增逻辑：遍历每一条 move line，把 origin_name 塞进去
#         if 'stock.move.line' in response['data']['records']:
#             move_lines = picking.move_line_ids
#             for idx, line in enumerate(move_lines):
#                 # 填充自定义原产地字段
#                 response['data']['records']['stock.move.line'][idx]['origin_name'] = line.origin_name or ''
#                 # 新增：客户参考号
#                 response['data']['records']['stock.move.line'][idx]['customer_reference'] = line.customer_reference or ''
#         return response
